package com.chenshu.shop.service;

import com.chenshu.shop.common.Constant;
import com.chenshu.shop.common.SecurityUtil;
import com.chenshu.shop.mapper.AdminMapper;
import com.chenshu.shop.model.Admin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2024-06-04
 * Time：13:55
 */
@Service
@Slf4j
public class AdminService {
    @Autowired
    AdminMapper adminMapper;

    public boolean login(String username, String password, HttpServletRequest request) {
        //用于判断账号密码是否正确
        boolean flag = false;
        Admin adminInfo = adminMapper.selectAdminByUsername(username);
        if (adminInfo != null) {
            flag = SecurityUtil.decrypt(password, adminInfo.getPassword());
        }
        //如果密码正确，就将管理员信息存入Session
        if (flag) {
            HttpSession session = request.getSession(true);
            session.setAttribute(Constant.SESSION_ADMIN_INFO_KEY, adminInfo);
            session.setAttribute("msg", "登录成功");
        }
        return flag;
    }

    public Integer adminSave(String username, String password) {
        return adminMapper.addAdmin(username, SecurityUtil.encrypt(password));
    }

    public List<Admin> getAllAdmins() {
        return adminMapper.selectAllAdmins();
    }

    public void deleteAdmin(Integer adminId) {
        int row = adminMapper.deleteAdmin(adminId);
        if (row == 1) {
            log.info("删除管理员成功！");
        } else {
            log.info("删除管理员失败！");
        }
    }

    public void updateAdminPassword(Integer id, String password) {
        Integer row = adminMapper.updateAdminPassword(id, SecurityUtil.encrypt(password));
        if (row == 1) {
            log.info("修改管理员密码成功！");
        } else {
            log.info("修改管理员密码失败！");
        }
    }
}
